package com.valdemar.demos;

import java.util.ArrayList;
import java.util.List;

import com.google.web.bindery.requestfactory.shared.Receiver;
import com.valdemar.android.givemeanswers.shared.GiveMeAnswersRequestFactory;
import com.valdemar.android.givemeanswers.shared.QuestionProxy;

import android.app.Activity;
import android.os.AsyncTask;
import android.widget.Toast;

public class AsyncFetchDemo extends AsyncTask<Long, Void, List<QuestionProxy>>
{
	private final Activity activity;
	private boolean newTask = false;

	public AsyncFetchDemo(Activity activity)
	{
		super();
		this.activity = activity;
	}

	@Override
	protected List<QuestionProxy> doInBackground(Long... arguments)
	{
		final List<QuestionProxy> list = new ArrayList<QuestionProxy>();

		// INSERT RPC HERE!
		GiveMeAnswersRequestFactory factory = Util.getRequestFactory(activity,
				GiveMeAnswersRequestFactory.class);

		if (arguments.length == 0 || arguments[0] == -1)
		{
			factory.questionRequest().queryQuestions().fire(new Receiver<List<QuestionProxy>>()
			{
				@Override
				public void onSuccess(List<QuestionProxy> arg0)
				{
					list.addAll(arg0);
				}
			});
		}
		else
		{
			newTask = true;
			factory.questionRequest().readQuestion(arguments[0]).fire(new Receiver<QuestionProxy>()
			{

				@Override
				public void onSuccess(QuestionProxy arg0)
				{
					list.add(arg0);
				}
			});
		}

		return list;
	}

	@Override
	protected void onPostExecute(List<QuestionProxy> result)
	{
		
		Toast.makeText(activity, "Temos Questions!! ;) #" + result.size(), Toast.LENGTH_SHORT).show();
		if (newTask)
		{
//			activity.addTasks(result);
		}
		else
		{
//			activity.setTasks(result);
		}
	}
}